package uf.audit.quene;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ActiveMQConnectionFactory;
import uf.audit.db.Marking;
import uf.audit.db.Test;
import uf.audit.db.TestOpt;

import javax.jms.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageQueue {
    public static final String TEST_QUEUE = "test-queue";
    public static boolean flag = false;
    private static ConnectionFactory connectionFactory = null;

    public Connection getConnection() throws JMSException {
        Connection connection = null;
        if (connectionFactory == null) {
            //1.创建工厂链接对象，指定IP和端口号
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
            ((ActiveMQConnectionFactory) connectionFactory).setTrustAllPackages(true);
            //2.使用链接工厂创建一个链接对象
            connection = connectionFactory.createConnection();
            //3.开启链接
            connection.start();
        }
        return connection;
    }

    public Session getSession(Connection conn) throws JMSException {
        return conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }

    public void release(Connection conn, Session session) throws JMSException {
        session.close();
        conn.close();
    }

    public void publishTestSubjects(HashMap<String, Object> map) throws JMSException {
        //5.使用会话对象创建目标对象，包含queue和topic（一对一和一对多）
        Connection conn = getConnection();
        Session session = getSession(conn);
        Queue queue = session.createQueue(TEST_QUEUE);
        //6.使用会话对象创建生产者对象
        MessageProducer producer = session.createProducer(queue);
        //7.使用会话对象创建一个消息对象
        ObjectMessage objectMessage = session.createObjectMessage();
        //8.发送消息
       /* for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setSex(String.valueOf(i));
            user.setUsername("name" + i);
            objectMessage.setObject(user);
            producer.send(objectMessage);
        }*/
        objectMessage.setObject(map);
        producer.send(objectMessage);
        //9.关闭资源
        producer.close();
        release(conn, session);
        flag = true;//全部消息发送完毕
    }

    public static class TestCustomer {
        private Connection connection;
        private Session session;

        public TestCustomer(Connection conn, Session session) {
            this.connection = conn;
            this.session = session;
        }

        public Connection getConnection() {
            return connection;
        }

        public void setConnection(Connection connection) {
            this.connection = connection;
        }

        public Session getSession() {
            return session;
        }

        public void setSession(Session session) {
            this.session = session;
        }
    }

    public TestCustomer receiveTestSubjects() throws JMSException, IOException {
        Connection connection = getConnection();
        Session session = getSession(connection);
        //5.使用会话创建目标对象，包含queue和topic
        Queue queue = session.createQueue(TEST_QUEUE);
        //6.使用会话创建消费者对象
        MessageConsumer messageConsumer = session.createConsumer(queue);
        //7.向customer对象中设置一个messageListener对象接收消息
        messageConsumer.setMessageListener(new MessageListener() {
            //@Override
            public void onMessage(Message message) {
                System.out.println("接受者：" + Thread.currentThread().getId());
                if (message != null) {
                    try {
                        HashMap<String, Object> map = (HashMap<String, Object>) ((ObjectMessage) message).getObject();
                        Object questions = map.get("questions");//题目列表
                        List<String> question_list = (List<String>) questions;
                        Object answer = map.get("answer");//答案列表
                        Map<String, String> answer_map = (Map<String, String>) answer;
                        //将所有试题放入数据库
                        for (int i = 0; i < question_list.size(); i++) {
                            String jsonstr = question_list.get(0);
                            JSONArray jsonArray = JSON.parseArray(jsonstr);
                            for (int l = 0; l < jsonArray.size(); l++) {
                                JSONObject json = jsonArray.getJSONObject(l);//获取jsonobject
                                JSONObject jsonObject = json.getJSONObject("columns");//通过可以获取value
                                jsonObject.remove("answer");
                                Test.dao.update(jsonObject);
                            }
                        }
                        //将所有的答案放入数据库
                        for (String key : answer_map.keySet()) {
                            String answer_item = answer_map.get(key);
                            JSONObject jsonObject = JSON.parseObject(answer_item);
                            TestOpt.dao.update(jsonObject);
                        }
                        //将所有分数更新列表存入数据库
                        Object marking_update = map.get("marking-update");//更新分数列表
                        if (marking_update != null) {
                            JSONObject jsonObject = (JSONObject) marking_update;
                            Marking.dao.update(jsonObject);
                        }
                        //将所有分数插入到数据库
                        Object marking_insert = map.get("marking-insert");//插入分数列表
                        if (marking_insert != null) {
                            Marking marking = (Marking) marking_insert;
                            marking.save();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        return new TestCustomer(connection, session);
    }

    /*public static void main(String[] args) {
        MessageQueue messageQuene = new MessageQueue();
        try {
            messageQuene.publishTestSubjects();
            if (flag) {
                messageQuene.receiveTestSubjects();
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}
